﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;

namespace SimpleWcf
{
    /// <summary>
    /// Lists out the available services.
    /// </summary>
    public class ServiceLister : System.Web.UI.Page, IRouteHandler
    {
        private readonly List<SimpleServiceRoute> serviceRoutes;
        public ServiceLister(List<SimpleServiceRoute> serviceRoutes)
        {
            this.serviceRoutes = serviceRoutes;
        }

        protected override void OnLoad(EventArgs e)
        {
            Response.Write("<html><head><style type=\"text/css\">#content{ font-size: 0.7em; padding-bottom: 2em; margin-left: 30px} body{margin-top: 0px; margin-left: 0px; color: #000000; font-family: verdana; background-color: white} p{margin-top: 0px; margin-bottom: 12px; color: #000000; font-family: verdana} pre{border-right: #f0f0e0 1px solid; padding-right: 5px; border-top: #f0f0e0 1px solid; margin-top: -5px; padding-left: 5px; font-size: 1.2em; padding-bottom: 5px; border-left: #f0f0e0 1px solid; padding-top: 5px; border-bottom: #f0f0e0 1px solid; font-family: courier new; background-color: #e5e5cc} .heading1{margin-top: 0px; padding-left: 15px; font-weight: normal; font-size: 26px; margin-bottom: 0px; padding-bottom: 3px; margin-left: -30px; width: 100%; color: #ffffff; padding-top: 10px; font-family: tahoma; background-color: #003366} .intro{margin-left: -15px}</style>");
            Response.Write("</head><body><div id=\"content\"><p class=\"heading1\">Service Listings</p><br/><p class=\"intro\">The following is a list of available services. To test a service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line.</p>");

            serviceRoutes.ForEach(WriteServiceInfo);

            Response.Write("</div></body></html>");
        }

        private void WriteServiceInfo(SimpleServiceRoute serviceRoute)
        {
            var serverPath = Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, String.Empty);
            var servicePath = VirtualPathUtility.ToAbsolute("~/" + serviceRoute.ServicePath);
            Response.Write(String.Format("<p class=\"intro\" style=\"font-weight:bold\"><a href=\"{0}\">{0}</a></p><p>{1}</p><pre>svcutil.exe <a href=\"{2}{0}\">{2}{0}</a></pre>", servicePath, serviceRoute.ServiceDescription, serverPath));
        }

        /// <summary>
        /// Provides the object that processes the request.
        /// </summary>
        /// <returns>
        /// An object that processes the request.
        /// </returns>
        /// <param name="requestContext">An object that encapsulates information about the request.</param>
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return this;
        }
    }
}